<template>
  <div class="main">
    <xr-header
      label="数据导入导出记录">
      <el-tooltip
        slot="otherLabel"
        effect="dark"
        placement="top"
        content="保留7天数据记录。">
        <i class="wk wk-help wk-help-tips" />
      </el-tooltip>
    </xr-header>
    <div class="main-body">
      <flexbox class="main-table-header">
        <el-select
          v-model="dataType"
          placeholder="类型"
          @change="handleChangeType">
          <el-option
            v-for="item in dataTypeList"
            :key="item.value"
            :label="item.name"
            :value="item.value" />
        </el-select>
        <el-date-picker
          v-model="dateTime"
          type="daterange"
          value-format="yyyy-MM-dd"
          range-separator="-"
          start-placeholder="开始时间"
          end-placeholder="结束时间" />
        <wk-user-dialog-select
          v-model="userList"
          :radio="false"
          collapse-tags
          placeholder="操作人" />
        <el-select
          v-model="apply"
          style="width: 160px;"
          placeholder="操作应用"
          clearable
          filterable
          :filter-method="(query)=> {filterMethod(query, 'applyList')}"
          @change="getModuleList">
          <el-option
            v-for="item in applyList"
            :key="item.value"
            :label="item.name"
            :value="item.value" />
        </el-select>
        <el-select
          v-model="module"
          style="width: 160px;"
          clearable
          placeholder="操作对象"
          filterable
          :filter-method="(query)=> {filterMethod(query, 'moduleList')}">
          <el-option
            v-for="item in moduleList"
            :key="item.value"
            :label="item.name"
            :value="item.value" />
        </el-select>

        <el-button
          type="primary"
          @click="refreshList">查询</el-button>
      </flexbox>
      <el-table
        v-loading="loading"
        :data="list"
        :class="WKConfig.tableStyle.class"
        :stripe="WKConfig.tableStyle.stripe"
        :height="tableHeight"
        class="main-table"
        highlight-current-row
        style="width: 100%;"
        @row-click="handleRowClick">
        <el-table-column
          v-for="(item, index) in fieldList"
          :key="index"
          :prop="item.prop"
          :label="item.label"
          :width="item.width"
          show-overflow-tooltip>
          <template slot-scope="{ row, column }">
            <template v-if="item.prop === 'sucNum'">
              导入成功 {{ row.importNum - row.failNum }} 条<span v-if="row.importType === 1">（其中覆盖 {{ row.updateNum }} 条）</span>
            </template>
            <template v-else-if="item.prop === 'failNum'">
              导入失败 {{ row[item.prop] }} 条
              <span v-if="row.importType === 2">（其中跳过 {{ row.skipNum }} 条，错误 {{ row.failNum - row.skipNum }} 条）</span>
              <span v-if="row.failNum" class="btn-link" @click="downloadData(row.failData)">，下载错误数据</span>
            </template>
            <template v-else-if="['failData', 'exportData'].includes(item.prop)">
              <span class="btn-link" @click="downloadData(row.importData || row.exportData)">下载{{ dataType === 'import' ? '导入' : '导出' }}数据</span>
            </template>
            <template v-else>{{ tableFormatter(row,column) }}</template>
          </template>
        </el-table-column>
        <el-table-column v-if="dataType === 'import'" />
      </el-table>
      <div class="p-contianer">
        <el-pagination
          :current-page="currentPage"
          :page-sizes="pageSizes"
          :page-size.sync="pageSize"
          :total="total"
          class="p-bar"
          background
          layout="prev, pager, next, sizes, total, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </div>
  </div>
</template>

<script>
import {
  biLogQueryImportLogsAPI,
  biLogQueryExportLogsAPI,
  biLogQueryApplyAPI,
  biLogQueryOperateObjectAPI
} from '@/api/admin/log'
import {
  crmDownImportErrorAPI
} from '@/api/adminMessage'

import XrHeader from '@/components/XrHeader'
import WkUserDialogSelect from '@/components/NewCom/WkUserDialogSelect'

import { objDeepCopy, downloadExcelWithResData } from '@/utils'
import PinyinMatch from 'pinyin-match'

export default {
  // 导入导出日志
  name: 'ImportExportLog',
  components: {
    XrHeader,
    WkUserDialogSelect
  },
  data() {
    return {
      loading: false, // 加载动画
      tableHeight: document.documentElement.clientHeight - 270, // 表的高度

      dateTime: [],
      userList: [],
      dataType: 'import', // 导入导出类型
      dataTypeList: [
        { name: '导入', value: 'import' },
        { name: '导出', value: 'export' }
      ],
      apply: '', // 应用详情
      applyList: [], // 应用列表
      applyListCopy: [], // 应用列表
      module: '', // 操作对象
      moduleList: [],
      moduleListCopy: [],
      list: [],
      currentPage: 1,
      pageSize: 15,
      pageSizes: [15, 30, 45, 60],
      total: 0,

      postParams: {}
    }
  },
  computed: {
    fieldList() {
      if (this.dataType === 'import') {
        return [
          {
            prop: 'userName',
            label: '操作人',
            width: 120
          },
          {
            prop: 'moduleName',
            label: '对象',
            width: 120
          },
          {
            prop: 'createTime',
            label: '导入时间',
            width: 200
          },
          {
            prop: 'importNum',
            label: '导入数据量',
            width: 120
          },

          {
            prop: 'sucNum',
            label: '导入成功量',
            width: 250
          },
          {
            prop: 'failNum',
            label: '导入失败量',
            width: 400
          },
          {
            prop: 'importType',
            label: '导入类型',
            width: 140
          },
          {
            prop: 'failData',
            label: '导入结果',
            width: 150
          }
        ]
      }

      return [
        {
          prop: 'userName',
          label: '操作人'
        },
        {
          prop: 'moduleName',
          label: '对象'
        },
        {
          prop: 'createTime',
          label: '导出时间'
        },
        {
          prop: 'exportNum',
          label: '导出数据量'
        },
        {
          prop: 'exportData',
          label: '导出结果'
        }
      ]
    }
  },
  mounted() {
    const startOfLastWeek = this.$moment().subtract(7, 'days').startOf('day').format('YYYY-MM-DD')
    const today = this.$moment().format('YYYY-MM-DD')
    this.dateTime = [startOfLastWeek, today]

    // 控制table的高度
    window.onresize = () => {
      this.tableHeight = document.documentElement.clientHeight - 270
    }

    this.getList()
    this.getApplyList()
  },
  methods: {
    /**
     * @description: 刷新数据
     * @return {*}
     */
    refreshList() {
      this.currentPage = 1
      this.getList()
    },

    /**
     * @description: 获取操作应用
     * @return {*}
     */
    getApplyList() {
      biLogQueryApplyAPI({ isModule: 1 }).then(res => {
        this.applyList = res.data || []
        this.applyListCopy = objDeepCopy(this.applyList)
      }).catch(() => {
      })
    },

    /**
     * @description: 获取操作对象
     * @return {*}
     */
    getModuleList() {
      this.module = ''
      this.moduleList = []
      this.moduleListCopy = []
      biLogQueryOperateObjectAPI({ apply: this.apply }).then(res => {
        this.moduleList = res.data || []
        this.moduleListCopy = objDeepCopy(this.moduleList)
      }).catch(() => {
      })
    },

    /**
     * @description: 更改类型
     * @return {*}
     */
    handleChangeType() {
      this.getList()
    },

    /**
     * @description: 获取列表数据
     * @return {*}
     */
    getList() {
      this.loading = true
      const params = {
        page: this.currentPage,
        limit: this.pageSize
      }
      if (this.userList && this.userList.length) {
        params.userList = this.userList
      }

      if (this.dateTime && this.dateTime.length) {
        params.startTime = this.dateTime[0]
        params.endTime = this.dateTime[1]
      }

      params.module = this.module
      params.apply = this.apply

      // 0 是普通 1 是设置
      params.type = 0

      this.postParams = params
      const request = {
        import: biLogQueryImportLogsAPI,
        export: biLogQueryExportLogsAPI
      }[this.dataType]
      request(params)
        .then(res => {
          this.list = res.data?.list || []
          this.total = res.data.totalRow
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },

    /**
     * 当某一行被点击时会触发该事件
     */
    handleRowClick(row, column, event) {
    //   const value = row[column.property]
    },

    /**
     * 下载错误数据、导入、导出数据
     */
    downloadData(downId) {
      crmDownImportErrorAPI({ messageId: downId })
        .then(res => {
          downloadExcelWithResData(res)
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },

    /**
     * 列表信息格式化
     */
    tableFormatter(row, column) {
      const value = row[column.property]
      if (column.property == 'importType') {
        return ['覆盖系统原有数据', '跳过', '更新系统原有数据'][value - 1]
      } else if (column.property === 'exportNum') {
        return value >= 0 ? value : ''
      }
      return value
    },

    /**
     * @description: 更改每页展示数量
     * @param {*} val
     * @return {*}
     */
    handleSizeChange(val) {
      this.pageSize = val
      this.getList()
    },

    /**
     * @description: 更改当前页数
     * @param {*} val 当前页数
     * @return {*}
     */
    handleCurrentChange(val) {
      this.currentPage = val
      this.getList()
    },

    /**
     * @description: 筛选
     * @param {*} query 关键词
     * @param {*} dataKey 数据源 变量名  加Copy为筛选数据源
     * @return {*}
     */
    filterMethod(query, dataKey) {
      if (query !== '') {
        this[dataKey] = this[`${dataKey}Copy`].filter(item => PinyinMatch.match(item.name, query))
      } else {
        this[dataKey] = objDeepCopy(this[`${dataKey}Copy`])
      }
    }
  }
}
</script>

  <style lang="scss" scoped>
  @import "./index.scss";

  ::v-deep .el-select {
    .el-select__tags {
      span {
        .el-tag:first-child {
          max-width: calc(100% - 60px);
        }
      }
    }
  }

  .btn-link {
    color: $--color-primary;
    cursor: pointer;
  }
  </style>

